package edu.xidian.sei.mlcs;

import java.util.Arrays;
import java.util.Comparator;

/**
 * 单个字符在所有字符串中的位置。
 * 
 * @author chaostone
 */
public class Location {

  public short[] index;

  private int hashCode;

  @Override
  public String toString() {
    String str = Arrays.toString(index);
    str = str.replaceAll(" ", "");
    return "(" + str.substring(1, str.length() - 1) + ")";
  }

  public Location(short[] index) {
    this.index = index;
    this.hashCode = buildHashCode();
  }

  private int buildHashCode() {
    int rs = 1;
    int i = 0;
    while (i < index.length) {
      rs = 31 * rs + index[i];
      i += 1;
    }
    return rs;
  }

  @Override
  public int hashCode() {
    return hashCode;
  }

  @Override
  public boolean equals(Object o) {
    Location bl = (Location) o;
    if (bl == this) return true;
    short[] b = bl.index;
    short[] a = index;
    int i = 0;
    boolean equals = true;
    while (i < a.length && equals) {
      if (a[i] != b[i]) {
        equals = false;
      }
      i += 1;
    }
    return equals;
  }

  /**
   * 最优路选择器
   */
  public static class Sorter implements Comparator<Location> {

    @Override
    public int compare(Location o1, Location o2) {
      int i = 0;
      short[] a = o1.index;
      short[] b = o2.index;
      int less = 0;
      int greate = 0;
      int lessIndex = 0;
      int oLessIndex = 0;
      while (i < a.length) {
        if (a[i] < b[i]) {
          less += 1;
          lessIndex += i;
        } else if (a[i] > b[i]) {
          greate += 1;
          oLessIndex += i;
        }
        i += 1;
      }
      if (less > greate) return -1;
      else if (less < greate) return 1;
      else return lessIndex - oLessIndex;
    }

  }

}
